﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.PersonService;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace RN.ERP.Web.Exam
{
    public partial class ZKZView : Page
    {
        #region Params
        
        PersonServiceClient client = new PersonServiceClient();
        private string HtmlTemplate;
        private string CurPageCode = "ZKZ";
        private string CurPage = "ZKZList.aspx";
        private List<Exam_ZKZ> ZKZList;
        private string AppID
        {
            get
            {
                return HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString();
            }
        }

        private string RoleID 
        {
            get
            {
                return Request["RoleID"];
            }
        }

        private string CorpUserGuid
        {
            get
            {
                return Request["CorpUserGuid"];
            }
        }
        
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ////读取HTML模板
                HtmlTemplate = LoadHtmlTemplate();
                
                if (!string.IsNullOrEmpty(Request.QueryString["ids"]) && !String.IsNullOrEmpty(HtmlTemplate))
                {
                    ////获取人员信息列表
                    ZKZList = GetZKZList(Request.QueryString["ids"]);
                    if (ZKZList != null && ZKZList.Count > 0)
                    {
                        rptZKZ.DataSource = ZKZList;
                        rptZKZ.DataBind();
                    }
                }
            }
        }

        /// <summary>
        /// 读取HTML模板
        /// </summary>
        private string LoadHtmlTemplate()
        {
            string strLine = string.Empty;
            string path = Server.MapPath("~/LoadFiles/" + AppID + "_ZKZ.htm");
            if (File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.Default);
                strLine = sr.ReadToEnd();
                sr.Close();
                fs.Close();
            }
            return strLine;
        }

        /// <summary>
        /// 获取人员信息列表
        /// </summary>
        private List<Exam_ZKZ> GetZKZList(string ids)
        {
            int count = 0;
            ////获取指定人员信息
            var list = client.GetZKZList(CurPageCode, RoleID, CurPage, AppID, 0, null, null, CorpUserGuid, null, ids, 0, 0, out count);
            if (list != null)
            {
                return JsonConvert.DeserializeObject<List<Exam_ZKZ>>(list);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 转义html信息绑定到前台
        /// </summary>
        /// <param name="id">报名子表id</param>
        /// <returns></returns>
        public string GetData(object id)
        {
            int subId = 0;
            int.TryParse(id.ToString(), out subId);
            Exam_ZKZ zkz = ZKZList.Where(m => m.ID == subId).FirstOrDefault();
            string strLine = HtmlTemplate;
            if (zkz != null)
            {
                ////正则表达式
                string tmpStr = @"\{\@([\w\W]*?)\}";
                ////匹配项
                MatchCollection Matches = Regex.Matches(strLine, tmpStr, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                foreach (Match NextMatch in Matches)
                {
                    string tmpStrTitle = NextMatch.Groups[0].Value;
                    string title = tmpStrTitle.TrimStart('@', '{').TrimEnd('}');
                    if (!tmpStrTitle.Contains("]."))
                    {
                        ////普通值类型的项
                        string newTitle = GetProperties(zkz, title);
                        strLine = strLine.Replace(tmpStrTitle, newTitle);
                    }
                    else
                    {
                        ////含有List的项
                        string[] strs = title.Split('.');
                        int index = 0;
                        int.TryParse(strs[0].Split(new string[] { "[", "]" }, StringSplitOptions.RemoveEmptyEntries)[1], out index);
                        ////index应在科目列表总数范围内
                        if (index < zkz.KMList.Length)
                        {
                            string newTitle = GetProperties(zkz.KMList[index], strs[1]);
                            strLine = strLine.Replace(tmpStrTitle, newTitle);
                        }
                        else
                        {
                            strLine = strLine.Replace(tmpStrTitle, string.Empty);
                        }
                    }
                }
            }
            return strLine;
        }

        /// <summary>
        /// 根据成员名称获取属性值
        /// </summary>
        /// <param name="t">实例</param>
        /// <param name="expression">表达式</param>
        /// <returns>属性值</returns>
        public string GetProperties<T>(T t, string expression)
        {
            string tStr = string.Empty;
            if (t == null)
            {
                return tStr;
            }
            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            if (properties.Length <= 0)
            {
                return tStr;
            }
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t, null);
                if (expression.Contains(".") && !expression.Contains("]"))
                {
                    ////非值类型数据项
                    if (item.PropertyType.ReflectedType != null)
                    {
                        string val = GetProperties(value, expression.Split('.')[1]);
                        if (!string.IsNullOrEmpty(val))
                        {
                            return val;
                        }
                    }
                }
                else
                {
                    ////普通值类型数据项
                    if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                    {
                        if (name == expression)
                        {
                            tStr = value != null ? value.ToString() : string.Empty;
                            break;
                        }
                    }
                }
            }
            return tStr;
        }
    }
}